<template>
  <div class="main-container">
    <div class="main" ref="containerRef"></div>

    <div class="tip" ref="tipRef">
      <div class="title">
        <span class="shine-text">{{ current.name }}</span>
      </div>
      <div class="info-item">
        <div class="name">全省家具企业数量：</div>
        <div class="value">{{ current.industrialAboveNumber }}家</div>
      </div>
      <div class="info-item">
        <div class="name">规上企业数量：</div>
        <div class="value">{{ current.industrialAboveRevenue }}家</div>
      </div>
      <div class="info-item">
        <div class="name">规上企业营收：</div>
        <div class="value">{{ current.totalIndustrialValue }}亿</div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import "echarts-gl";

const chinaJson = require("@/assets/mapJson/china.json");
const chinaMapBg = require("@/assets/images/map/china-map-bg2.png");

const containerRef = ref(null);
const tipRef = ref(null);
const jsonData = ref({});
const current = ref({});
const getJsonData = async () => {
  try {
    const res = await fetch("/json/map-api.json");
    jsonData.value = await res.json(); // 解析 JSON 格式
  } catch (err) {
    console.error("读取失败：", err);
  }
};
const initEchart = () => {
  let data = jsonData.value.chinaChart.heatData;
  let echartsData = jsonData.value.chinaChart.echartsData;
  let cutTime = jsonData.value.chinaChart.cutTime;
  console.log("jsonData.value.chinaChart", jsonData.value.chinaChart);

  //   let data = echartsData.heatData;
  // 扩大热力图密度（可选：每个点复制4次增强效果）
  let areaData = [];
  data.forEach((item) => {
    areaData.push(...new Array(4).fill(item));
  });

  // 计算最大最小值用于 visualMap
  let mapMax = Math.max(...data.map((item) => item[2]));
  let mapMin = Math.min(...data.map((item) => item[2]));
  let myChart = echarts.init(containerRef.value);
  echarts.registerMap("china", chinaJson);

  let option = {
    visualMap: {
      bottom: 20,

      z: 5,
      left: 10,
      show: false,
      inRange: {
        color: ["#90ff07", "#ffff00", "#ff4d4f"], // 蓝色 -> 黄色 -> 红色
      },
      // color: ['#fa0023', '#84d100', '#90ff07', '#edcc00'],
      min: mapMin,
      max: mapMax,
      calculable: true,
      textStyle: {
        color: "#fff",
        fontSize: 12,
      },
    },
    grid: {
      height: "100%",
      width: "100%",
    },
    geo: {
      map: "china",
      aspectScale: 1,
      zoom: 1.1,
      roam: false,
      itemStyle: {
        areaColor: {
          type: "radial",
          x: 0.5,
          y: 0.5,
          r: 0.8,
          colorStops: [
            {
              offset: 0,
              color: "#09132c",
            },
            {
              offset: 1,
              color: "#274d68",
            },
          ],
        },
        shadowColor: "RGBA(179, 242, 253, 0.6)",
        borderWidth: 2,
        shadowOffsetX: 0,
        shadowOffsetY: 6,
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",

            opacity: 0,
            label: {
              show: false,
              color: "#009cc9",
            },
          },
        },
      ],
    },
    series: [
      {
        type: "map",
        map: "china",
        zoom: 1.1,
        aspectScale: 1,
        itemStyle: {
          areaColor: {
            image: chinaMapBg,
            repeat: "no-repeat",
          },
          borderColor: "RGBA(179, 242, 253, 1)",
          borderWidth: 2,
          shadowColor: "rgba(0, 0, 0, 0.5)",
          shadowBlur: 10,
        },
        data: areaData,
      },
      {
        type: "heatmap",
        coordinateSystem: "geo",
        data: areaData,
        pointSize: 5, // 可以根据需要调整点的大小
        blurSize: 8, // 显著缩小扩散范围
        maxOpacity: 0.8,
        minOpacity: 0.3, // 保持最低透明度，避免完全消失
        itemStyle: {
          color: "#333", // 热点的颜色
        },
      },
    ],
  };

  myChart.setOption(option);
  // 数据预处理：确保 site 是数字

  echartsData.forEach((item) => {
    item.site = [parseFloat(item.site[0]), parseFloat(item.site[1])];
  });
  console.log("echartsData", echartsData);

  let timer = null;
  // 自动轮播函数
  const showTip = (() => {
    let i = 0;
    const len = echartsData.length;
    return () => {
      const point = echartsData[i];
      current.value = point;
      const pos = myChart.convertToPixel("geo", current.value.site);
      const tip = tipRef.value;
      if (tip) {
        tip.style.left = pos[0] - 60 + "px";
        tip.style.top = pos[1] - 100 + "px";
        tip.style.display = "block";
      }
      i = (i + 1) % len;
    };
  })();
  // 点击事件
  myChart.off("click");
  myChart.on("click", (params) => {
    if (params.componentType !== "series" || params.seriesType !== "map")
      return;

    const provinceName = params.name;
    const matched = echartsData.find((item) => item.name === provinceName);
    const tip = tipRef.value;

    if (matched) {
      current.value = matched;
      const pos = myChart.convertToPixel("geo", current.value.site);
      if (tip) {
        tip.style.left = pos[0] - 60 + "px";
        tip.style.top = pos[1] - 100 + "px";
        tip.style.display = "block";
      }

      // 重置自动轮播
      if (timer) clearInterval(timer);
      timer = setInterval(showTip, cutTime);
    } else {
      if (tip) tip.style.display = "none";
    }
  });
  // 启动自动轮播
  if (timer) clearInterval(timer);
  timer = setInterval(showTip, cutTime);
};
onMounted(async () => {
  await getJsonData();
  initEchart();
});
</script>
<style lang="less" scoped>
.main-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .main {
    width: 1000px;
    height: 400px;
  }
  .tip {
    position: absolute;
    box-sizing: border-box;
    padding: 8px 12px;
    display: none;
    background: url("@/assets/images/map/dialogBg.png") no-repeat;
    background-size: 100% 100%;

    .title {
      font-size: 20px;
      font-weight: bold;
      padding: 3px 0px;
      .shine-text {
        color: rgba(255, 255, 255, 0.7);
      }
    }

    .info-item {
      margin-top: 3px;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .name {
        color: rgba(255, 255, 255, 0.7);
        font-size: 18px;
      }
      .value {
        color: rgba(255, 255, 255, 0.7);
        font-size: 20px;
      }
    }
  }
}
</style>
